package com.example.springboot.service.Impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.common.ResultCode;
import com.example.springboot.common.config.JwtTokenUtils;
import com.example.springboot.dao.AdminMapper;
import com.example.springboot.dao.MessageMapper;
import com.example.springboot.dao.UserMapper;
import com.example.springboot.domain.po.Account;
import com.example.springboot.domain.po.Admin;
import com.example.springboot.domain.po.Message;
import com.example.springboot.domain.po.User;
import com.example.springboot.exception.CustomException;
import com.example.springboot.service.MessageService;
import com.example.springboot.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author：伐柯梦姝
 * @Package：com.example.springboot.service.Impl
 * @Project：springboot
 * @name：MessageServiceImpl
 * @Date：2025/3/4 22:47
 * @Filename：MessageServiceImpl
 * @for:
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    @Resource
    private MessageMapper messageMapper;
    @Resource
    private AdminMapper adminMapper;
    @Resource
    private UserMapper userMapper;

    @Override
    public Message add(Message message) {
        message.setTime(DateUtil.now());
        messageMapper.insert(message);
        return message;
    }

    @Override
    public void delete(Integer id) {
        this.removeById(id);
    }

    @Override
    public Message findById(Integer id) {
        return messageMapper.selectById(id);
    }

    @Override
    public List<Message> findAll() {
        Account currentUser = JwtTokenUtils.getCurrentUser();
        if (ObjectUtil.isNull(currentUser)) {
            //throw new CustomException("-1", "登录失效，请重新登录");
            throw new CustomException(ResultCode.LOGIN_CHECK_ERROR);
        }
        List<Message> list = this.findByParentId(0);
        for (Message message : list) {
            setData(message);
            List<Message> children = this.findByParentId(message.getId());
            if (CollectionUtil.isNotEmpty(children)) {
                for (Message child : children) {
                    setData(child);
                }
                message.setChildren(children);
            }
        }
        return list;
    }

    @Override
    public void setData(Message message) {
        if (1 == message.getRole()) {
            Admin admin = adminMapper.selectById(message.getUserId());
            message.setUsername(admin.getUsername());
            message.setAvatar(admin.getAvatar());
        }
        if (2 == message.getRole()) {
            User user = userMapper.selectById(message.getUserId());
            message.setUsername(user.getUsername());
            message.setAvatar(user.getAvatar());
        }
    }

    @Override
    public PageInfo<Message> findPage(Message search, Integer pageNum, Integer pageSize) {
        Account currentUser = JwtTokenUtils.getCurrentUser();
        if (ObjectUtil.isNull(currentUser)) {
            throw new CustomException(ResultCode.USER_NOT_LOGIN);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Message> all = findByCondition(search, currentUser);
        for (Message message : all) {
            Integer role = message.getRole();
            if (1 == role) {
                Admin admin = adminMapper.selectById(message.getUserId());
                message.setUsername(admin.getUsername());
            } else {
                User user = userMapper.selectById(message.getUserId());
                message.setUsername(user.getUsername());
            }
        }
        return PageInfo.of(all);
    }

    @Override
    public List<Message> findByCondition(Message search, Account currentUser) {
        if (1 == currentUser.getRole()) {
            return this.findBySearch(search, null, null);
        } else {
            return this.findBySearch(search, currentUser.getId(), currentUser.getRole());
        }
    }


    public List<Message> findByParentId(Integer parentId){
        return this.lambdaQuery()
                .eq(ObjectUtil.isNotEmpty(parentId), Message::getParentId, parentId)
                .list();
    }

    public List<Message> findBySearch(Message search, Integer userId, Integer userRole){
        List<Message> list = this.lambdaQuery()
                .like(ObjectUtil.isNotEmpty(search) && ObjectUtil.isNotEmpty(search.getContent()),
                        Message::getContent, search.getContent())
                .eq(ObjectUtil.isNotEmpty(userId), Message::getUserId, userId)
                .eq(ObjectUtil.isNotEmpty(userRole), Message::getRole, userRole)
                .list();
        return list;
    }

}
